package com.athuiju.fenxiaoback.controller;


import com.athuiju.fenxiaoback.entity.UcenterMember;
import com.athuiju.fenxiaoback.entity.vo.*;
import com.athuiju.fenxiaoback.service.OssService;
import com.athuiju.fenxiaoback.service.UcenterMemberService;
import com.athuiju.fenxiaoback.utils.JwtUtils;
import com.athuiju.fenxiaoback.utils.MD5;
import com.athuiju.fenxiaoback.utils.R;
import com.athuiju.fenxiaoback.utils.anno.LoginUser;
import com.athuiju.fenxiaoback.utils.anno.Token;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author athuiju
 * @since 2021-06-30
 */
@Api(description = "用户",tags = "用户")
@RestController
@RequestMapping("/fenxiaoback/ucenter-member")
public class UcenterMemberController {
    @Autowired
    private UcenterMemberService memberService;


    @Autowired
    private OssService ossService;


    /**
     * 自定义token解析...
     * @return
     */
    @ApiOperation(value = "用户---修改昵称---自定义token")
    @GetMapping("updateNickNamecustomtoken")
    @Token
    public R updateNickNamecustomtoken(@LoginUser CurrentUser user){
        System.out.println("自定义token111111");
        System.out.println(user);
        //String memberid = JwtUtils.getMemberIdByJwtToken(request);
        //UcenterMember member = memberService.getById(memberid);
        //member.setNickname(nickname);
        //boolean b = memberService.updateById(member);
        //if (b){
        //    return R.ok().put("msg","修改成功");
        //}
        //return R.ok().put("msg","修改失败");
        return R.ok();
    }











    /**
     * 设置密码---已登录
     *
     * @param
     */
    @ApiOperation(value = "设置密码---已登录")
    @PostMapping("setPassword")
    public R setPassword(@RequestBody UpdatePasswordVo updatePasswordVo, HttpServletRequest request) {
        System.out.println(updatePasswordVo);
        String againPassword = updatePasswordVo.getAgainPassword();
        String newPassword=updatePasswordVo.getNewPassword();

        if(!StringUtils.isEmpty(againPassword) && !StringUtils.isEmpty(newPassword)){
            if (againPassword.equalsIgnoreCase(newPassword)){
                String memberid = JwtUtils.getMemberIdByJwtToken(request);
                UcenterMember member = memberService.getById(memberid);
                member.setPassword(MD5.encrypt(updatePasswordVo.getNewPassword()));
                memberService.updateById(member);
                return R.ok().put("msg","密码设置成功");
            }
        }
        return R.error().put("code","500").put("msg","密码设置失败,检查新旧密码");
    }





    @ApiOperation(value = "用户---修改性别")
    @GetMapping("updateSex/{sex}")
    public R updateSex(@ApiParam(value = "1:男,0:女",example = "1")@PathVariable Integer sex, HttpServletRequest request){

        String memberid = JwtUtils.getMemberIdByJwtToken(request);

        UcenterMember member = memberService.getById(memberid);
        member.setSex(sex);
        boolean b = memberService.updateById(member);
        if (b){
            return R.ok().put("msg","修改成功");
        }
        return R.ok().put("msg","修改失败");
    }



    /**
     * 文件上传
     *
     * @param file
     */
    @ApiOperation(value = "修改头像")
    @PostMapping("uploadAvatar")
    public R uploadAvatar(@ApiParam(name = "file", value = "文件", required = true) @RequestParam(value="file",required=false) MultipartFile file,HttpServletRequest request) {
        String memberid = JwtUtils.getMemberIdByJwtToken(request);
        String url = ossService.uploadFileAvatar(file,memberid);
        return R.ok().put("url", url);
    }


    @ApiOperation(value = "用户---修改昵称")
    @GetMapping("updateNickName/{nickname}")
    public R updateNickName(@PathVariable String nickname, HttpServletRequest request){
        String memberid = JwtUtils.getMemberIdByJwtToken(request);
        UcenterMember member = memberService.getById(memberid);
        member.setNickname(nickname);
        boolean b = memberService.updateById(member);
        if (b){
            return R.ok().put("msg","修改成功");
        }
        return R.ok().put("msg","修改失败");
    }






    @ApiOperation(value = "查看用户资料")
    @GetMapping("getUserInfo")
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = UcenterMember.class),
    })
    public R getUserInfo(HttpServletRequest request){
        String memberid = JwtUtils.getMemberIdByJwtToken(request);
        UcenterMember memberinfo = memberService.getById(memberid);



        return R.ok().put("data",memberinfo).put("two_constellation",memberinfo.getConstellation().substring(0,2));
    }


    @ApiOperation(value = "修改出生日期")
    @GetMapping("addAge/{birthday}")
    public R addAge( @ApiParam("示例:2021-05-05")  @PathVariable("birthday") String birthday, HttpServletRequest request) {
        String memberid = JwtUtils.getMemberIdByJwtToken(request);
        String[] births= {"水瓶座","双鱼座","白羊座","金牛座","双子座","巨蟹座","狮子座","处女座","天秤座","天蝎座","射手座","摩羯座"};
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date birth=null;
        String constellation="暂无";
        try {
            birth = sdf.parse(birthday);


            if(birth.compareTo(new Date())==1){
                return R.error().put("msg","日期不能超过当前时间");
            }
            Calendar cal=Calendar.getInstance();
            cal.setTime(birth);
            int month=cal.get(Calendar.MONTH);
            constellation=births[month];
        } catch (ParseException e) {
            return R.ok().put("msg","日期格式有误");
        }


        UcenterMember member = memberService.getOne(new QueryWrapper<UcenterMember>().eq("id", memberid));
        Integer age=null;
        try {
            age = getAge(birth);
            member.setAge(age);
            member.setBirthday(birth);
            member.setConstellation(constellation);
        } catch (Exception e) {
            member.setAge(null);
            return  R.error().put("msg","修改失败");
        }

        memberService.updateById(member);
        return R.ok().put("msg","修改成功").put("newAge",member.getAge());
    }

    public static  Integer getAge(Date birthDay) throws Exception {
        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDay)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);  //当前年份
        int monthNow = cal.get(Calendar.MONTH);  //当前月份
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        int age = yearNow - yearBirth;
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;
            }else{
                age--;
            } } return age; }

}

